#include "MultChannel.h"

MultChannel::~MultChannel()
{
    for(uint8_t* cp : channels)
        free(cp);
}

bool MultChannel::TryLoad(std::istream &i)
{
    this->multChannelHead.TryLoad(i);
    int c_length = multChannelHead.GetH() * multChannelHead.GetW();
    for(uint8_t* cp : channels)
        free(cp);
    channels.clear();
    for(int k = 0; k < multChannelHead.GetChannelCount(); ++k)
    {
        auto cp = static_cast<uint8_t *>(malloc(c_length));
        if(cp)
            channels.emplace_back(cp);
        else
        {
            throw StrException("申请内存空间失败");
            return false;
        }
    }
    for(uint8_t* cp : channels)
        for(int k = 0; k < c_length; ++k)
            Load(i, cp[k]);
    return true;
}

bool MultChannel::TryDump(std::ostream &o)
{
    multChannelHead.TryDump(o);
    int c_length = multChannelHead.GetH() * multChannelHead.GetW();
    for(uint8_t* cp : channels)
    {
        for(int k = 0; k < c_length; ++k)
        {
            Dump(o, cp[k]);
        }
    }
    return true;
}

bool MultChannel::IsDumpable()
{
    if(!multChannelHead.IsDumpable())
        return false;
    if(channels.size() != multChannelHead.GetChannelCount())
        return false;
    for(uint8_t* cp : channels)
        if(!cp)
            return false;
    return true;
}
